#nullable disable
using ERPBackend.Data;
using ERPBackend.Models;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Linq;

namespace ERPBackend.Services
{
    public class MaterialService : IMaterialService
    {
        private readonly ApplicationDbContext _context;

        public MaterialService(ApplicationDbContext context)
        {
            _context = context ?? throw new ArgumentNullException(nameof(context));
        }


        public async Task<IEnumerable<Material>> GetAllMaterialsAsync()
        {
            var materials = await _context.Materials
                .Include(m => m.SecondLevelCategory)
                .ThenInclude(s => s.FirstLevelCategory)
                .ToListAsync();
            
            // 处理可能的空引用
            return materials?
                .Select(m => {
                    if (m.SecondLevelCategory != null)
                    {
                        // 访问SecondLevelCategory的属性是安全的
                        m.SecondLevelCategory.FirstLevelCategory = m.SecondLevelCategory.FirstLevelCategory;
                    }
                    return m;
                })
                ?? Enumerable.Empty<Material>();
        }

        public async Task<Material?> GetMaterialByIdAsync(int id)
        {
            var material = await _context.Materials
                .Include(m => m.SecondLevelCategory)
                .ThenInclude(s => s.FirstLevelCategory)
                .FirstOrDefaultAsync(m => m.Id == id);
            
            // 处理可能的空引用
            if (material?.SecondLevelCategory != null)
            {
                // 访问SecondLevelCategory的属性是安全的
                var firstLevelCategory = material.SecondLevelCategory.FirstLevelCategory;
            }
            
            return material;
        }

        public async Task<IEnumerable<Material>> GetMaterialsBySecondLevelCategoryIdAsync(int secondLevelCategoryId)
        {
            var materials = await _context.Materials
                .Include(m => m.SecondLevelCategory)
                .ThenInclude(s => s.FirstLevelCategory)
                .Where(m => m.SecondLevelCategoryId == secondLevelCategoryId)
                .ToListAsync();
            
            // 处理可能的空引用
            return materials?
                .Select(m => {
                    if (m.SecondLevelCategory != null)
                    {
                        // 访问SecondLevelCategory的属性是安全的
                        m.SecondLevelCategory.FirstLevelCategory = m.SecondLevelCategory.FirstLevelCategory;
                    }
                    return m;
                })
                ?? Enumerable.Empty<Material>();
        }

        public async Task<Material> CreateMaterialAsync(Material material)
        {
            // 验证二级分类是否存在
            var secondLevelCategoryExists = await _context.SecondLevelCategories
                .AnyAsync(s => s.Id == material.SecondLevelCategoryId);
            if (!secondLevelCategoryExists)
            {
                throw new ArgumentException("Invalid second level category id");
            }

            // 验证物料编码是否唯一
            if (await _context.Materials.AnyAsync(m => m.MaterialCode == material.MaterialCode))
            {
                throw new ArgumentException("Material code already exists");
            }

            // 自动生成物料编码的逻辑可以在这里添加

            _context.Materials.Add(material);
            await _context.SaveChangesAsync();
            return material;
        }

        public async Task<bool> UpdateMaterialAsync(Material material)
        {
            // 检查物料是否存在
            var existingMaterial = await _context.Materials.FindAsync(material.Id);
            if (existingMaterial == null)
            {
                return false;
            }

            // 验证二级分类是否存在
            var secondLevelCategoryExists = await _context.SecondLevelCategories
                .AnyAsync(s => s.Id == material.SecondLevelCategoryId);
            if (!secondLevelCategoryExists)
            {
                return false;
            }

            // 物料编码不可修改
            if (existingMaterial.MaterialCode != material.MaterialCode)
            {
                throw new ArgumentException("Material code cannot be modified");
            }

            // 更新属性
            existingMaterial.MaterialName = material.MaterialName;
            existingMaterial.Specification = material.Specification;
            existingMaterial.SecondLevelCategoryId = material.SecondLevelCategoryId;
            existingMaterial.Description = material.Description;
            existingMaterial.Status = material.Status;

            _context.Entry(existingMaterial).State = EntityState.Modified;
            await _context.SaveChangesAsync();
            return true;
        }

        public async Task<bool> DeleteMaterialAsync(int id)
        {
            var material = await _context.Materials.FindAsync(id);
            if (material == null)
            {
                return false;
            }

            // 可以在这里添加业务逻辑，例如检查是否有相关的其他数据

            _context.Materials.Remove(material);
            await _context.SaveChangesAsync();
            return true;
        }
    }
}